import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:gim_plugin/gim_plugin.dart';
import 'package:gim_plugin_example/pages/overlay_liver/artc/liver_1v1_room_overlay.dart';
import 'package:gim_plugin_example/pages/tab_conversation/tab_conversation.dart';
import 'package:gim_plugin_example/pages/tab_conversation/tab_conversation_store.dart';
import 'package:gim_plugin_example/pages/tab_user_list/tab_user_list.dart';
import 'package:gim_plugin_example/pages/tab_user_list/tab_user_list_store.dart';
import 'package:gim_plugin_example/sdk/gim_sdk.dart';
import 'package:gim_plugin_example/utils/logger_utils.dart';
import 'package:provider/provider.dart';

class AppTabs extends StatelessWidget {
  @override
  Widget build(BuildContext context) => MultiProvider(providers: [
        ChangeNotifierProvider(create: (_) => AppTabsStore()),
        ChangeNotifierProvider(create: (_) => TabConversationStore()),
        ChangeNotifierProvider(create: (_) => TabUserListStore()),
      ], child: _AppTabs());
}

class _AppTabs extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _AppTabsState();
}

class _AppTabsState extends State<_AppTabs> with WidgetsBindingObserver {
  final List<Widget> tabs = [TabConversation(), TabUserList()];

  @override
  void initState() {
    WidgetsBinding.instance?.addObserver(this);
    gimSdk.gim.addSignalingFn(signalingCb);
    //一秒之主动触发检查最后一条信令
    Future.delayed(const Duration(seconds: 1)).then((_) => gimSdk.gim.checkLastSignaling());
    super.initState();
  }

  @override
  void dispose() {
    WidgetsBinding.instance?.removeObserver(this);
    gimSdk.gim.delSignalingFn(signalingCb);
    super.dispose();
  }

  void signalingCb(SignalingMsg msg) async {
    if (msg.event == EventTypes.SignalingInvite) {
      //如果目前正在接听电话，等待五秒再确认一次，如果还在接电话，那么拒绝这次来电
      if (!openHolding(msg)) {
        Future.delayed(const Duration(seconds: 5)).then((value) {
          if (!openHolding(msg)) {
            gimSdk.gim.signalingReject(signalingId: msg.signalingId!, extData: json.encode({
              'msg': '目前正忙'
            }));
          }
        });
      }
    }
  }

  bool openHolding(SignalingMsg msg) {
    var extData = json.decode(msg.extData);
    //启动holding页面
    return liver1v1roomOverlay.open(context,
        videoCall: extData['videoCall'],
        channelName: extData['channelName'],
        master: false,
        signalingId: msg.signalingId!,
        remoteUid: extData['uid'],
        remoteNickname: extData['nickname'],
        remoteAvatar: extData['avatar']);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    switch (state) {
      case AppLifecycleState.resumed:
        gimSdk.gim.resetOnFrontDesk(flag: true);
        loggerDebug("页面状态前台", state);
        break;
      case AppLifecycleState.paused:
        gimSdk.gim.resetOnFrontDesk(flag: false);
        loggerDebug("页面状态后台", state);
        break;
      case AppLifecycleState.inactive:
        // TODO: Handle this case.
        break;
      case AppLifecycleState.detached:
        // TODO: Handle this case.
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Selector(
          builder: (BuildContext context, int idx, Widget? child) => tabs[idx],
          selector: (BuildContext context, AppTabsStore store) => store.tabIdx),
      bottomNavigationBar: buildBottomNavigationBar(),
    );
  }

  BottomNavigationBar buildBottomNavigationBar() {
    AppTabsStore store = context.watch<AppTabsStore>();
    return BottomNavigationBar(
      currentIndex: store.tabIdx,
      onTap: (idx) {
        store.switchTab(idx);
      },
      type: BottomNavigationBarType.fixed,
      selectedItemColor: Colors.black,
      unselectedItemColor: Colors.black.withOpacity(0.5),
      selectedLabelStyle: const TextStyle(fontWeight: FontWeight.w400),
      unselectedLabelStyle: const TextStyle(fontWeight: FontWeight.w400),
      selectedFontSize: 12,
      unselectedFontSize: 12,
      items: [
        tabItem(icon: 'icons/tab_msg.png', label: '消息'),
        tabItem(icon: 'icons/tab_user.png', label: '用户'),
      ],
    );
  }

  BottomNavigationBarItem tabItem({required String icon, required String label}) {
    return BottomNavigationBarItem(
        icon: Opacity(child: Image.asset(icon, width: 26, height: 26), opacity: 0.5),
        activeIcon: Image.asset(icon, width: 26, height: 26),
        label: label);
  }
}

class AppTabsStore extends ChangeNotifier {
  int tabIdx = 0;

  void switchTab(int idx) {
    tabIdx = idx;
    notifyListeners();
  }
}
